package com.tengju.bff.application.wx;

import com.tengju.data.domain.model.wx.WxActivateStatus;
import com.tengju.data.domain.model.wx.WxUserInfo;
import com.tengju.data.domain.model.wx.WxUserInfoRepository;
import com.tengju.support.domain.model.wx.WechatUser;
import com.tengju.support.domain.model.wx.WechatUserStatus;
import com.tengju.support.domain.service.WeiXinCompanyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李大仙
 * @date: 2021/12/20 9:52 上午
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class WxUserActiveStatusJobService {

    private final WxUserInfoRepository wxUserInfoRepository;
    private final WeiXinCompanyService weiXinCompanyService;


    int coreSize = Runtime.getRuntime().availableProcessors();
    int maxPoolSize = Math.round(((float) (coreSize * 80)) / 10);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            coreSize, maxPoolSize,
            1000, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(200000));

    public void execute() {
        List<WxUserInfo> localUserInfoList = wxUserInfoRepository.selectAll();
        for (WxUserInfo wxUserInfo : localUserInfoList) {
            threadPoolExecutor.execute(() -> {
                WechatUser wechatUser = weiXinCompanyService.getUser(wxUserInfo.getIdCode().toString());
                Integer status = Optional.ofNullable(wechatUser)
                        .map(WechatUser::getStatus)
                        .map(WechatUserStatus::getVal)
                        .orElse(0);
                Integer localActivateStatus = Optional.ofNullable(wxUserInfo.getWxActivateStatus())
                        .map(WxActivateStatus::getCode)
                        .orElse(0);
                if (!status.equals(localActivateStatus)) {
                    wxUserInfo.setWxActivateStatus(WxActivateStatus.form(status));
                    wxUserInfoRepository.updateActivateStatus(wxUserInfo);
                }
            });
        }
    }


}
